#include <bits/stdc++.h>

using namespace std;

// 至少有1位重复的数字个数
// 给定正整数n，返回在[1, n]范围内至少有1位重复数字的正整数个数
// 测试链接 : https://leetcode.cn/problems/numbers-with-repeated-digits/

class Solution 
{
public:
    int numDupDigitsAtMostN(int n) 
    {
        return n - countSpecialNumbers(n);
    }

    int countSpecialNumbers(int n)
    {
        int len = 1;
        int offset = 1;
        int tmp = n / 10;
        while(tmp > 0)
        {
            ++len;
            tmp /= 10;
            offset *= 10;
        }
        int cnt[len];
        cnt[0] = 1;
        for(int i = 1, k = 10 - len + 1; i < len; ++i, ++k)
        {
            cnt[i] = cnt[i - 1] * k;
        }
        int ans = 0;
        if(len >= 2)
        {
            ans = 9;
            for(int i = 2, s = 9, k = 9; i < len; ++i, --k)
            {
                s *= k;
                ans += s;
            }
        }
        int first = n / offset;
        ans += (first - 1) * cnt[len - 1];
        ans += f(cnt, n, len - 1, offset / 10, 1 << first);
        return ans;
    }

    int f(int* cnt, int num, int len, int offset, int status)
    {
        if(len == 0) return 1;
        int first = (num / offset) % 10;
        int ans = 0;
        for(int cur = 0; cur < first; ++cur)
        {
            if((status & (1 << cur)) == 0)
            {
                ans += cnt[len - 1];
            }
        }
        if((status & (1 << first)) == 0)
        {
            ans += f(cnt, num, len - 1, offset / 10, status | (1 << first));
        }
        return ans;
    }
};


class Solution 
{
public:
    int numDupDigitsAtMostN(int n) 
    {
        auto s = to_string(n);
        int m = s.size(), dp[m][1 << 10];
        memset(dp, -1, sizeof(dp));
        function<int(int, int, bool, bool)> f = [&](int i, int mask, bool is_limit, bool is_num) -> int
        {
            if(i == m) return is_num;
            if(!is_limit && is_num && dp[i][mask] != -1) return dp[i][mask];
            int ans = 0;
            if(!is_num) ans = f(i + 1, mask, false, false);
            int up = is_limit ? s[i] - '0' : 9;
            for(int d = 1 - is_num; d <= up; ++d)
            {
                if((mask & (1 << d)) == 0)
                {
                    ans += f(i + 1, mask | (1 << d), is_limit && d == up, true);
                }
            }
            if(!is_limit && is_num) dp[i][mask] = ans;
            return ans;
        };
        return n - f(0, 0, true, false);
    }
};